#-*- coding: utf-8 -*-
import urllib2
import sys
import ssl
import json
import time
import smtplib
from email.mime.text import MIMEText

#12306证书不安全...
ssl._create_default_https_context = ssl._create_unverified_context

#Ticket infomation.
#站点信息需抓包 TO_FILL
from_station = 'BJP'
to_station = 'CSQ'
#Time format is y-m-d, day must two digits. TO_FILL
train_date = '2015-10-01'
#Ticket type.
ticket_type = 'ADULT'

#Web infomation.
query_url_prefix = 'https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.'

#Main infomation. TO_FILL
_mail_user = ''
_mail_pwd = ''
_mail_suffix = ''
_mail_signature = ''
_mail_list = []
 
#Filter infomationi. TO_FILL
"""
G 高铁
D 动车
T 特快
K 快车
Z 直达
"""
train_code = ['G', 'D']
"""
商务座->swz_num
一等座->zy_num
二等座->ze_num
高级软卧->gr_num
软卧->rw_num
软座->rz_num
特等座->tz_num
无座->wz_num
硬卧->yw_num
硬座->yz_num
其他几种类型未知
"""
seat_type = ['zy_num', 'ze_num', 'swz_num']

def send_mail(to_list, sub, content):
	me = _mail_signature + '<' + _mail_user + '@' + _mail_suffix + '>'
	msg = MIMEText (content , _subtype = 'html' , _charset = 'utf-8')
	msg['Subject'] = sub
	msg['From'] = me
	msg['To'] = ";".join (to_list)
	print msg['To']
	try:
		s = smtplib.SMTP ()
		s.connect ('smtp.' + _mail_suffix)
		s.login (_mail_user, _mail_pwd)
		s.sendmail (me, to_list, msg.as_string ())
		s.close ()
		return True
	except Exception, e:
		print str (e)
		return False

def debug_info (list):
	print '车次\t', 'gg\t', '高软\t', 'qt\t', '软卧\t', '软座\t', '特等\t',\
		  '无座\t', 'yb\t', '硬卧\t', '硬座\t', '二等\t', '一等\t', '商务'
	for train in list:
		info = train['queryLeftNewDTO']
		print info['station_train_code'], '\t', info['gg_num'], '\t', info['gr_num'], \
			  '\t', info['qt_num'], '\t', info['rw_num'], '\t', info['rz_num'], '\t', \
			  info['tz_num'], '\t', info['wz_num'], '\t', info['yb_num'], '\t', \
			  info['yw_num'], '\t', info['yz_num'], '\t', info['ze_num'], '\t', \
			  info['zy_num'], '\t', info['swz_num']

def packet_url ():
	info = 'train_date=' + train_date + \
		   '&leftTicketDTO.from_station=' + from_station + \
		   '&leftTicketDTO.to_station=' + to_station + \
		   '&purpose_codes=' + ticket_type
	return query_url_prefix + info

def get_return_packet (url):
	req = urllib2.Request (url)
	return json.loads (urllib2.urlopen (req).read ())['data']

def train_filter (list):
	if train_code:
		ret = []
		for train in list:
			code = train['queryLeftNewDTO']['station_train_code']
			for filter in train_code:
				if code[0] == filter:
					ret.append (train)
		return ret
	return list

def ticket_filter (list):
	if seat_type:
		ret = []
		for train in list:
			info = train['queryLeftNewDTO']
			for str in seat_type:
				#print info['station_train_code'], info[str]
				if info[str] != u'无' and info[str] != '--' and info[str] != '*':
					ret.append (train)
		return ret
	return list

def get_left_ticket_info ():
	url = packet_url ()
	train_info = get_return_packet (url)
	train_info = train_filter (train_info)
	train_info = ticket_filter (train_info)
	if train_info:
		debug_info (train_info)
		mail_content = ''
		for train in train_info:
			mail_content += train['queryLeftNewDTO']['station_train_code']
			mail_content += '\n'
		if _mail_list:
			send_mail (_mail_list, "找到合适车票", mail_content)
		return True
	else:
		print '找不到符合条件的车次'
		return False


if __name__ == '__main__':
	while (not get_left_ticket_info ()):
		time.sleep (60)
